package com.crl.module.code.custom
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	/**
	 * 
	 * @author crl
	 * 
	 * eg
	 * 		var decoder:AJpegDecoder=new AJpegDecoder();
			decoder.decodeCompleteHandler=function(data:AJpegData):void{
				var bitmap:Bitmap=new Bitmap(data.png);
				if(bitmap.width>stage.stageWidth){
					bitmap.y=height+100;
				}else{
					bitmap.x=width+100;
				}
				addChild(bitmap);
				
				trace(data.meta.readUTF())
			}
			decoder.deconde(bytes);
	 * 
	 */	
	public class AJpegDecoder
	{
		public var decodeCompleteHandler:Function;
		
		private var loader:Loader;
		
		private var alphaBytes:ByteArray;
		private var meataBytes:ByteArray;
		
		public function AJpegDecoder()
		{
			loader=new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,jpgcompleteHandler);
		}
		
		private function jpgcompleteHandler(event:Event):void{
			var bitmapdata:BitmapData=(loader.content as Bitmap).bitmapData;
			
			var w:int=bitmapdata.width;
			var h:int=bitmapdata.height;
			var rect:Rectangle=new Rectangle(0,0,w,h);
			var alphaBitmapData:BitmapData=new BitmapData(w,h,true,0);
			
			alphaBitmapData.copyPixels(bitmapdata,rect,new Point(0,0));
			alphaBitmapData=this.setAlphasToBitmapdata(alphaBitmapData,alphaBytes);
			
			if(decodeCompleteHandler !=null){
				decodeCompleteHandler(new AJpegData(alphaBitmapData,meataBytes));
			}
			//this.dispatchEvent();
		}
		
		
		private function setAlphasToBitmapdata(bitmapdata:BitmapData,alphas:ByteArray):BitmapData{
			alphas.position=0;
			
			var w:int=bitmapdata.width;
			var h:int=bitmapdata.height;
			var alp:uint;
			var rgb:uint;
			var i:int=0,j:int=0;
			
			bitmapdata.lock();
			while(i<w){
				j=0;
				while(j<h){
					alp=alphas.readUnsignedByte();
					rgb=uint(bitmapdata.getPixel32(i, j) & 0xffffff);
					bitmapdata.setPixel32(i, j, uint(rgb | alp << 24));
					j++
				}
				i++;
			}
			bitmapdata.unlock();
			return bitmapdata;
		}
		
		
		public function deconde(bytes:ByteArray):void{
			var head:uint=bytes.readUnsignedInt();
			if(head != AJpegData.HEAD){
				throw new Error("类型不对");
			}
			var jpg:ByteArray=new ByteArray();
			var len:uint=bytes.readUnsignedInt();
			bytes.readBytes(jpg,0,len);
			jpg.uncompress();
			loader.loadBytes(jpg);
			
			alphaBytes=new ByteArray();
			var alen:uint=bytes.readUnsignedInt();
			bytes.readBytes(alphaBytes,0,alen);
			alphaBytes.uncompress();
			
			meataBytes=new ByteArray();
			bytes.readBytes(meataBytes);
		}
		
		
	}
}